<template>
  <div class="user-follow-page">
    <div class="tabs">
      <div
        :class="['tab', { active: type === 'follow' }]"
        @click="switchTab('follow')"
      >
        关注 <span class="count">{{ followCount }}</span>
      </div>
      <div
        :class="['tab', { active: type === 'fan' }]"
        @click="switchTab('fan')"
      >
        粉丝 <span class="count">{{ fanCount }}</span>
      </div>
    </div>

    <div class="user-item" v-for="u in userList" :key="u.userId">
      <img :src="u.avatar" class="avatar" @click.stop="goUserHome(u.userId)" />
      <div class="info">
        <div class="username">{{ u.username }}</div>
        <div class="level">{{ u.signature || '无签名' }}</div>
      </div>
      <button class="follow-btn" @click="toggleFollow(u)">
        {{ u.isMutualFollow ? '互相关注' : u.isFollowed ? '已关注' : '关注' }}
      </button>
    </div>

    <teleport to="body">
      <div v-if="showDialog" class="custom-dialog-mask">
        <div class="custom-dialog">
          <p class="dialog-text">
            你确定要{{ dialogActionText }} {{ dialogUser?.username }} 吗？
          </p>
          <div class="dialog-buttons">
            <button @click="handleDialogConfirm" class="confirm-btn">
              确认
            </button>
            <button @click="handleDialogCancel" class="cancel-btn">取消</button>
          </div>
        </div>
      </div>
    </teleport>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getFollows, getFans, followUser, getUserInfo } from '@/apis/user'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()

// 新增跳转方法
const goUserHome = (userId) => {
  router.push({
    path: `/home/user/${userId}`,
  })
}

const type = ref(route.query.type || 'follow')
const uid = route.params.userId
const followCount = ref(0)
const fanCount = ref(0)
const userList = ref([])

const fetchList = async () => {
  if (!uid) return
  try {
    const res =
      type.value === 'follow' ? await getFollows(uid) : await getFans(uid)
    if (res.code === '200') {
      const dataList = Array.isArray(res.data) ? res.data : res.data.list || []
      userList.value = dataList
    } else {
      ElMessage.error(res.message || '获取用户关系失败')
    }
  } catch (err) {
    ElMessage.error('网络异常，请稍后重试')
  }
}
const fetchUserCount = async () => {
  try {
    const res = await getUserInfo(uid)
    if (res.code === '200') {
      followCount.value = res.data.followCount || 0
      fanCount.value = res.data.fanCount || 0
    }
  } catch {
    console.warn('获取关注/粉丝数失败')
  }
}
const switchTab = (newType) => {
  router.replace({ query: { type: newType } })
}

watch(
  () => route.query.type,
  async (newVal) => {
    type.value = newVal || 'follow'
    await fetchUserCount()
    await fetchList()
  }
)

onMounted(() => {
  fetchUserCount()
  fetchList()
})

// ✅ 弹窗相关逻辑
const showDialog = ref(false)
const dialogUser = ref(null)
const dialogActionText = ref('关注')
let nextFollowStatus = false

const toggleFollow = (user) => {
  dialogUser.value = user
  nextFollowStatus = !user.isFollowed
  dialogActionText.value = nextFollowStatus ? '关注' : '取消关注'
  showDialog.value = true
}

const handleDialogConfirm = async () => {
  showDialog.value = false
  if (!dialogUser.value) return
  try {
    const res = await followUser(dialogUser.value.userId, nextFollowStatus)
    if (res.code === '200') {
      dialogUser.value.isFollowed = nextFollowStatus
      dialogUser.value.isMutualFollow =
        nextFollowStatus && dialogUser.value.isFan // ✅ 互相关注判断
      ElMessage.success(`${dialogActionText.value}成功`)
    } else {
      ElMessage.error(res.message || `${dialogActionText.value}失败`)
    }
  } catch {
    ElMessage.error('关注操作失败')
  }
}

const handleDialogCancel = () => {
  showDialog.value = false
}
</script>

<style scoped>
.user-follow-page {
  padding: 16px;
}
.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}
.back-btn {
  background: none;
  border: none;
  font-size: 14px;
  color: #007bff;
  display: flex;
  align-items: center;
  cursor: pointer;
}
.tabs {
  display: flex;
  border-bottom: 1px solid #eee;
  margin-bottom: 12px;
}
.tab {
  padding: 10px 16px;
  cursor: pointer;
  font-size: 15px;
}
.tab.active {
  font-weight: bold;
  border-bottom: 2px solid #000;
}
.user-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.user-item {
  display: flex;
  align-items: center;
  background: #f9f9f9;
  padding: 12px;
  border-radius: 8px;
}
.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 12px;
}
.info {
  flex: 1;
}
.username {
  font-size: 15px;
  font-weight: bold;
}
.level {
  font-size: 13px;
  color: #888;
}
.follow-btn {
  font-size: 13px;
  padding: 6px 12px;
  border: 1px solid #000;
  border-radius: 6px;
  background: #fff;
  cursor: pointer;
}

.custom-dialog-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.4);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}
.custom-dialog {
  background-color: #fff;
  padding: 20px 30px;
  border-radius: 10px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  min-width: 280px;
  text-align: center;
}
.dialog-text {
  font-size: 16px;
  margin-bottom: 20px;
}
.dialog-buttons {
  display: flex;
  justify-content: space-between;
  gap: 20px;
}
.confirm-btn,
.cancel-btn {
  flex: 1;
  padding: 10px;
  font-size: 14px;
  border-radius: 6px;
  cursor: pointer;
  border: none;
}
.confirm-btn {
  background-color: #000;
  color: #fff;
}
.cancel-btn {
  background-color: #fff;
  color: #000;
  border: 1px solid #ccc;
}
</style>
